package club.hicode.daydayup.netty.udp.agent;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.IOException;

/**
 * @author leizhenyang
 */
@Slf4j
public class UDPServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        String body = packet.content().toString(CharsetUtil.UTF_8);
        System.out.println(DateUtil.now() + "  收到消息" + body);
        String id = analysisId(body);
        String template = "{\"InvokeID\":\"{}\",\"result\":\"{}\"}";

        String sendStr = StrUtil.format(template, id, DateUtil.now());

        System.out.println("  服务端回执消息：" + sendStr);
        DatagramPacket sendPacket = new DatagramPacket(Unpooled.copiedBuffer(sendStr.getBytes()), packet.sender());
        ctx.channel().writeAndFlush(sendPacket);
    }

    /**
     * 从json字符串中解析id
     *
     * @param jsonStr json字符串
     * @return id
     * @throws IOException
     */
    public static String analysisId(String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = mapper.readTree(jsonStr);
        } catch (IOException e) {
            log.error(" 响应字符串:{} 解析Id出现异常 ", jsonStr);
            e.printStackTrace();
            return StrUtil.EMPTY;
        }
        String id = jsonNode.path("InvokeID").asText();
        return id;
    }

    @Test
    public void formatTest() {
        String template = "{'InvokeID':'{}','result':'{}'}";

        String sendStr = StrUtil.format(template, 123, DateUtil.now());
        System.out.println(sendStr);

    }

    @Test
    public void test3() {
        String template = "{'InvokeID':'{}','result':'xx'}";
        String sendBody = StrUtil.format(template, StrUtil.uuid());
        System.out.println(sendBody);


    }

    @Test
    public void analysis4() throws IOException {
        String str = "{\"InvokeID\":\"4c8ae9e4-2bf2-4692-a193-504135266c0d\",\"result\":\"xx\"}";
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(str);
        System.out.println(jsonNode);
    }
}
